<!-- 商品发布 - 权限设置 -->
<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" :disabled="isDetail">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>商品权限</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        无权限浏览则该商品不展示给会员；无购买权限仅支持查看商品，不支持购买商品。
      </span>
    </div>
    <el-form-item label="浏览权限" prop="browseAuthority">
      <el-checkbox-group v-model="formData.browseAuthority" @change="onChangeBrowseAuthority">
        <template
          v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_BROWSE_AUTHORITY)"
          :key="dict.value"
        >
          <el-checkbox
            :value="dict.value"
            v-if="dict.value == 0"
            :disabled="
              formData.browseAuthority?.includes(1) ||
              formData.browseAuthority?.includes(2) ||
              formData.browseAuthority?.includes(4)
            "
          >
            {{ dict.label }}
          </el-checkbox>
          <el-checkbox :value="dict.value" v-else :disabled="formData.browseAuthority?.includes(0)">
            {{ dict.label }}
          </el-checkbox>
        </template>
      </el-checkbox-group>
      <div
        v-if="formData.browseAuthority?.includes(1)"
        class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
      >
        <el-tag
          effect="dark"
          class="mr-15px"
          size="large"
          :closable="!isDetail"
          v-for="(item, index) in formData.browseMember"
          :key="item.id"
          @close="formData.browseMember?.splice(index, 1)"
        >
          {{ getMemberLevelInfo(item)?.name }}</el-tag
        >
        <el-button @click="addMemberLevel('browseMember')">添加会员等级</el-button>
      </div>
      <div
        v-if="formData.browseAuthority?.includes(2)"
        class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
      >
        <el-tag
          effect="dark"
          class="mr-15px"
          size="large"
          :closable="!isDetail"
          v-for="(item, index) in formData.browsePaidMember"
          :key="item"
          @close="formData.browsePaidMember?.splice(index, 1)"
        >
          {{ getPaidMemberLevelInfo(item).spuName }}</el-tag
        >
        <el-button @click="addPaidMemberLevel('browsePaidMember')">添加付费会员等级</el-button>
      </div>
      <div
        v-if="formData.browseAuthority?.includes(4)"
        class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
      >
        <el-tag
          effect="dark"
          class="mr-15px"
          size="large"
          :closable="!isDetail"
          v-for="(item, index) in formData.browseTags"
          :key="item"
          @close="formData.browseTags?.splice(index, 1)"
        >
          {{ getTagInfo(item).name }}</el-tag
        >
        <el-button @click="addMemberTag('browseTags')">添加标签组</el-button>
      </div>
    </el-form-item>

    <el-form-item label="购买权限" prop="buyAuthority" @change="onChangeBuyAuthority">
      <el-checkbox-group v-model="formData.buyAuthority">
        <template
          v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_BUY_AUTHORITY)"
          :key="dict.value"
        >
          <el-checkbox
            :value="dict.value"
            v-if="dict.value == 0"
            :disabled="
              formData.buyAuthority?.includes(1) ||
              formData.buyAuthority?.includes(2) ||
              formData.buyAuthority?.includes(4)
            "
          >
            {{ dict.label }}
          </el-checkbox>
          <el-checkbox :value="dict.value" v-else :disabled="formData.buyAuthority?.includes(0)">
            {{ dict.label }}
          </el-checkbox>
        </template>
      </el-checkbox-group>
      <div
        v-if="formData.buyAuthority?.includes(1)"
        class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
      >
        <el-tag
          effect="dark"
          class="mr-15px"
          size="large"
          :closable="!isDetail"
          v-for="(item, index) in formData.buyMember"
          :key="item.id"
          @close="formData.browseMember?.splice(index, 1)"
        >
          {{ getMemberLevelInfo(item).name }}</el-tag
        >
        <el-button @click="addMemberLevel('buyMember')">添加会员等级</el-button>
      </div>
      <div
        v-if="formData.buyAuthority?.includes(2)"
        class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
      >
        <el-tag
          effect="dark"
          class="mr-15px"
          size="large"
          :closable="!isDetail"
          v-for="(item, index) in formData.buyPaidMember"
          :key="item.id"
          @close="formData.buyPaidMember?.splice(index, 1)"
        >
          {{ getPaidMemberLevelInfo(item).spuName }}</el-tag
        >
        <el-button @click="addPaidMemberLevel('buyPaidMember')">添加付费会员等级</el-button>
      </div>
      <div
        v-if="formData.buyAuthority?.includes(4)"
        class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
      >
        <el-tag
          effect="dark"
          class="mr-15px"
          size="large"
          :closable="!isDetail"
          v-for="(item, index) in formData.buyTags"
          :key="item.id"
          @close="formData.buyTags?.splice(index, 1)"
          >{{ getTagInfo(item).name }}</el-tag
        >
        <el-button @click="addMemberTag('buyTags')">添加标签组</el-button>
      </div>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      商品限购
    </div>
    <el-form-item label="商品限购" prop="quotaAuthority.selectId">
      <div class="w-100%">
        <el-radio-group v-model="formData.quotaAuthority" @change="onChangeQuotaAuthority">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_QUOTA)"
            :key="dict.value"
            :value="dict.value"
            >{{ dict.label }}
          </el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <el-form-item label="单次最少" prop="singleQuotaMini" v-if="formData.quotaAuthority == 2">
      <div>
        <el-input-number
          v-model="formData.singleQuotaMini"
          :precision="0"
          :max="999"
          :step="1"
          placeholder="请输入统一限购,最大数量999"
          class="w-120!"
          :controls="false"
        />

        <Explaintip msg="单次最少购买X件，少于X件不能购买。" />
      </div>
    </el-form-item>
    <el-form-item label="单次最多" prop="singleQuotaMax" v-if="formData.quotaAuthority == 2">
      <el-input-number
        v-model="formData.singleQuotaMax"
        :precision="0"
        :max="999"
        :step="1"
        placeholder="请输入统一限购,最大数量999"
        class="w-120!"
        :controls="false"
      />
    </el-form-item>
    <el-form-item label="永久限购" prop="permanentQuota" v-if="formData.quotaAuthority == 2">
      <el-input-number
        v-model="formData.permanentQuota"
        :precision="0"
        :max="999"
        :step="1"
        placeholder="请输入统一限购,最大数量999"
        class="w-120!"
        :controls="false"
      />
    </el-form-item>
    <!--todo 单一限购暂不处理 -->
    <!-- <template v-if="formData.quotaAuthority?.selectId == 3">
      <el-form-item v-if="!formData.specType">
        <SkuListPermission
          ref="skuListPermissionRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="ruleConfig"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListPermission
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListPermission
            ref="skuListPermissionRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="ruleConfig"
          />
        </el-form-item>
      </template>
    </template> -->
  </el-form>
  <!-- 会员等级选择 -->
  <MemberLevelSelect ref="MemberLevelSelectRef" @success="setMemberLevel" />
  <!-- 付费会员等级选择 -->
  <PaidMemberLevelSelect ref="PaidMemberLevelSelectRef" @success="setPaidMemberLevel" />
  <!-- 会员标签组选择 -->
  <MemberTagSelect ref="MemberTagSelectRef" @success="setMemberTag" />
</template>
<script lang="ts" setup>
/** todo 注释掉的都是单一限购 并且还未与后台对接 */
import type { Spu } from '@/api/mall/product/spu'
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { copyValueToTarget } from '@/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import {
  getPropertyList,
  PropertyAndValues
  // RuleConfig
  // SkuListPermission
} from '@/views/mall/product/spu/components/index'
// import { ProductSkuSetTypeEnum } from '@/utils/constants'

defineOptions({ name: 'ProductPermissionForm' })
//todo 单一限购 暂时注释
// const ruleConfig: RuleConfig[] = []
// let productQuotaType = getIntDictOptions(DICT_TYPE.PRODUCT_QUOTA_TYPE)
// productQuotaType.forEach((ele) => {
//   ruleConfig.push({
//     name: `${ProductSkuSetTypeEnum.QUOTATYPE.type}${ele.value}`,
//     rule: (arg) => arg >= 1,
//     message: '商品限购数量必须大于等于 1 ！！！'
//   })
// })
const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  activeName: propTypes.string.def(''),
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  memberLevelList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  paidMemberLevelList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  tagsList: {
    type: Array as PropType<any[]>,
    default: () => []
  }
})

const formRef = ref() // 表单Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
// const skuListPermissionRef = ref() // 商品属性列表 Ref

// 表单数据
const formData = ref<Spu>({
  specType: false, // 商品规格
  skus: [],
  browseAuthority: [0], //浏览权限 0 不限制 1 指定会员等级可见 2 指定付费会员等级可见 4指定标签组可见
  browseMember: undefined, //浏览权限 会员
  browsePaidMember: undefined, //浏览权限 付费会员
  browseTags: undefined, //浏览权限 标签组
  buyAuthority: [0], //购买权限
  buyMember: undefined, //购买权限 会员
  buyPaidMember: undefined, //购买权限 付费会员
  buyTags: undefined, //购买权限 标签组
  quotaAuthority: 0, //商品限购
  singleQuotaMini: undefined, //商品限购 单次最少
  singleQuotaMax: undefined, //商品限购 单次最多
  permanentQuota: undefined //商品限购 永久限购
})
// 表单规则
const rules = reactive({
  // browseAuthority: [required],
  // buyAuthority: [required]
  // quotaAuthority: [required]
})
/**  浏览权限发生变化时*/
const onChangeBrowseAuthority = () => {
  if (formData.value.browseAuthority?.includes(0)) {
    formData.value.browseAuthority = [0]
  }
}
/**  购买权限发生变化时*/
const onChangeBuyAuthority = () => {
  if (formData.value.buyAuthority?.includes(0)) {
    formData.value.buyAuthority = [0]
  }
}
/** 选择限购 */
const onChangeQuotaAuthority = () => {}

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }

    copyValueToTarget(formData.value, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => formData.value,
  () => {
    Object.assign(props.propFormData, formData.value)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 获取会员等级 */
const memberLevelList = computed(() => {
  return props.memberLevelList
})

const getMemberLevelInfo = (id) => {
  if (!id) {
    return
  }
  let info = memberLevelList.value.find((ele: any) => {
    return ele.id == id
  })
  return info
}
/** 获取付费会员等级 */
const paidMemberLevelList = computed(() => {
  return props.paidMemberLevelList
})
const getPaidMemberLevelInfo = (id) => {
  if (!id) {
    return
  }
  let info = paidMemberLevelList.value.find((ele: any) => {
    return ele.spuId == id
  })
  return info
}
/** 获取标签组 */
const tagsList = computed(() => {
  return props.tagsList
})
const getTagInfo = (id) => {
  if (!id) {
    return
  }
  let info = tagsList.value.find((ele: any) => {
    return ele.id == id
  })
  return info
}
/** 会员等级管理*/
const MemberLevelSelectRef = ref()
const addMemberLevelType = ref('') //选择的类型
// 门店选中
const addMemberLevel = (type: string) => {
  addMemberLevelType.value = type
  MemberLevelSelectRef.value.open(formData.value[addMemberLevelType.value])
}
const setMemberLevel = (levelList) => {
  formData.value[addMemberLevelType.value] = levelList
}
/** 付费会员等级管理*/
const PaidMemberLevelSelectRef = ref()
const addPaidMemberLevelType = ref('') //选择的类型
// 门店选中
const addPaidMemberLevel = (type: string) => {
  addPaidMemberLevelType.value = type
  PaidMemberLevelSelectRef.value.open(formData.value[addPaidMemberLevelType.value])
}
const setPaidMemberLevel = (levelList) => {
  formData.value[addPaidMemberLevelType.value] = levelList
}
/** 会员标签管理*/
const MemberTagSelectRef = ref()
const MemberTagType = ref('') //选择的类型
// 门店选中
const addMemberTag = (type: string) => {
  MemberTagType.value = type
  MemberTagSelectRef.value.open(formData.value[MemberTagType.value])
}
const setMemberTag = (tagList) => {
  formData.value[MemberTagType.value] = tagList
}

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    await unref(formRef)?.validate()
    // 保存时剔除不必要的字段
    if (formData.value.browseAuthority?.includes(0)) {
      formData.value.browseMember = undefined
      formData.value.browsePaidMember = undefined
      formData.value.browseTags = undefined
    }
    if (formData.value.buyAuthority?.includes(0)) {
      formData.value.buyMember = undefined
      formData.value.buyPaidMember = undefined
      formData.value.buyTags = undefined
    }
    if (formData.value.quotaAuthority == 0) {
      formData.value.singleQuotaMini = undefined
      formData.value.singleQuotaMax = undefined
      formData.value.permanentQuota = undefined
    }

    // 校验通过更新数据
    Object.assign(props.propFormData, formData.value)
  } catch (e) {
    message.error('【商品权限】不完善，请填写相关信息')
    emit('update:activeName', 'permission')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
</script>
